import os

from sphinx import addnodes
from sphinx import roles

class ExampleXRefRole(roles.XRefRole):
    def process_link(self, env, refnode, has_explicit_title, title, target):
        examples = os.path.join('..', 'examples')
        for root, dirs, files in os.walk(examples):
            if target in files:
                target = os.path.join(root, target)
                return title, '/' + target

def setup(app):
    app.add_role("example",
            ExampleXRefRole(nodeclass=addnodes.download_reference))
